<!--班车详情页-->
<template>
    <el-container class="layout-container" v-loading="loading">
        <!--<el-header class="layout-header">
            <div>
                <el-button v-if="isEdit" v-show="readonly" type="primary" @click="readonly = false">编辑</el-button>
                <el-button v-show="!readonly" type="default" @click="readonly = true">取消</el-button>
                <el-button v-show="!readonly" type="primary" @click="handleSave">保存</el-button>
            </div>
            <div>

                &lt;!&ndash;<el-button type="primary" @click="handleExport('school')">导出站点总名单</el-button>&ndash;&gt;
                &lt;!&ndash;<el-button type="primary" @click="handleExport('go')">导出班车去程名单</el-button>&ndash;&gt;
                &lt;!&ndash;<el-button type="primary" @click="handleExport('leave')">导出班车回程名单</el-button>&ndash;&gt;
            </div>
        </el-header>-->
        <el-container class="layout-container">
            <el-aside class="layout-aside">
                    <div class="nav-warp">
                        <el-scrollbar>
                        <div class="nav-item" :class="{'active': activePage === 0}" @click="togglePage(0)">班车管理</div>
                        <div class="nav-item" v-if="isSeeTicket" :class="{'active': activePage === 1}" @click="togglePage(1)">班车套票</div>
                        <div class="nav-item" v-if="isSeeStop" :class="{'active': activePage === 2}" @click="togglePage(2)">班车站点</div>
                        <div class="nav-item" v-if="isSeeSeat" :class="{'active': activePage === 3}" @click="togglePage(3)">班车座位表</div>
                        <div class="nav-item" v-if="isSeeSchool" :class="{'active': activePage === 4}" @click="togglePage(4)">班车站点(讫地)表</div>
                        </el-scrollbar>
                    </div>
            </el-aside>
            <el-main class="layout-main" v-show="activePage === 0">

                <div class="btns-wrap">
                    <el-button v-if="isEdit" v-show="readonly" type="primary" @click="readonly = false">编辑</el-button>
                    <el-button v-show="!readonly" type="default" @click="readonly = true">取消</el-button>
                    <el-button v-show="!readonly" type="primary" @click="handleSave">保存</el-button>
                </div>

                <div class="subfield-layout">
                    <div class="subfield-wrap">
                        <div class="subfield-title">信息</div>
                        <div class="subfield-main">
                            <div class="subfield-content">
                                <m-form ref="formRef" :fields="fieldList" :readonly="readonly" :value="mData">
                                    <template #mySlot>
                                        <div class="tips">
                                            在{{startDate}}开始，在优先购票名单内的人可以购票，在{{newDate}}开始，所有人可以购票。
                                        </div>
                                    </template>
                                </m-form>
                            </div>
                        </div>
                    </div>
                </div>
            </el-main>
            <el-main class="layout-main ref-wrap" v-show="activePage !== 0">
                <s-ticket :shuttle-data="mData" v-if="isSeeTicket && activePage === 1"></s-ticket>
                <s-stop :shuttle-data="mData" v-if="isSeeStop && activePage === 2"></s-stop>
                <s-seat v-model:shuttle-data="mData" :handleSave2="handleSave2" v-if="isSeeSeat && activePage === 3"></s-seat>
                <s-school :shuttle-data="mData" v-if="isSeeSchool && activePage === 4"></s-school>
            </el-main>
        </el-container>
    </el-container>
</template>

<script setup>
  import {ref,reactive,provide, defineEmits,defineProps,watch} from 'vue';
  import {useRoute} from 'vue-router'
  import MForm from '@/components/common/Form/Form'
  import RelPage from './RelPage.vue'
  import STicket from './STicket_xinban'
  import SStop from './SStop_xinban'
  import SSeat from './SSeat_xinban'
  import SSchool from './SSchool_xinban'
  import {getAllShuttle, editAllShuttle,} from '@/request/api/basicData'
  import {refOpt} from "../const";
  import {hasSeeAuthority,getAuthority} from "../../utils/permission";
  import {crtTimeFtt} from "../../utils/utils";
  import {ElMessage} from "element-plus";

  const props = defineProps(['data']),
    emit = defineEmits(['save']);

  const fieldList = ref([
    {label: '班车编号',field_id: 'shuttle_id',type: 'text',col: 2,disabled: true},
    {label: '班车名称',field_id: 'shuttle_name',type: 'text',col: 2},
    {label: '班车内部编号',field_id: 'inside_shuttle_id',type: 'text',col: 2},
    {label: '班车类型',field_id: 'shuttle_type',type: 'picklist',options: [{label:'车站客运班车',value:'车站客运班车'},{label:'定制',value:'定制'}],defaultValue:'车站客运班车',col: 2 },

    {...refOpt.packag_label_id,col:2,},
    {...refOpt.packag_label_name,col:2},

    {label: '说明',field_id: 'mark',type: 'textarea',col: 4},
    {label: '服务时段',field_id: 'service_period',type: 'text',col: 2},
    {label: '座位总数',field_id: 'seat_total',type: 'number',col: 2,precision: 4},
    {...refOpt.shuttle_seat_id,col: 2},
    {...refOpt.shuttle_seat_name,col: 2},
    {label: '开售时间起',field_id: 'sell_dateime_start',type: 'datetime',col: 2},
    {label: '开售时间止',field_id: 'sell_dateime_end',type: 'datetime',col: 2},
    {label: '优先购票分钟',field_id: 'priority_minute',type: 'number',col: 1 },
    {col: 3,isSlot: true},
    {label: '班车有效时间起',field_id: 'effective_time_start',type: 'datetime',col: 2},
    {label: '班车有效时间止',field_id: 'effective_time_end',type: 'datetime',col: 2},
    {...refOpt.operation_group_id,col: 2},
    {...refOpt.operation_group_name,col: 2},
    {label: '使用标识',field_id: 'is_used',type: 'bool',col: 2},
    {label: '群二维码',field_id: 'group_qrcode',type: 'picture',limit: 1,col: 2},
  ])

let mData = ref({}),
  formRef = ref(null),
  activePage = ref(0),
  readonly = ref(true),
  loading = ref(false),
  isEdit = ref(true),     //班车是否可编辑
  isSeeTicket = ref(true),    //班车套票是否可见
  isSeeStop = ref(true),    //班车站点是否可见
  isSeeSeat = ref(true),    //班车座位是否可见
  isSeeSchool = ref(true),    //班车站点是否可见
  startDate = ref(''),    //班车优先购票时间
  newDate = ref(''),  //班车没有优先购票开售时间
  activeRow_id = ref('');
  getRefPermission();
  //数据变化
  /*function handleChange(val) {
    console.log(1,val);
    let {field,value} = val,
      {field_id,type,entityKey} = field;
      data[field_id] = value;
    console.log(data);
  }*/
  watch(() => props.data,(newVal) =>{
    getDetailData(newVal.shuttle_id)
    /*let obj = {};
    fieldList.value.forEach(item =>{
      let val = newVal[item.show_field || item.field_id]
      val && (obj[item.field_id] = val)
    });
    mData.value = obj;*/
  },{immediate: true});
  watch([() => mData.value.sell_dateime_start,() => mData.value.priority_minute],(newVal) =>{
    // let startTime = newVal[0] && crtTimeFtt(newVal[0],'YYYY年MM月DD日HH时mm分ss秒');
    let startTime = newVal[0] && new Date(newVal[0]).getTime(),
    newTime = startTime && (startTime + (newVal[1] || 0) * 60 *1000);//单位分钟转换成秒
    let _startDate = startTime && crtTimeFtt(startTime,'YYYY年MM月DD日HH时mm分ss秒') || '',
      _newDate = newTime && crtTimeFtt(newTime,'YYYY年MM月DD日HH时mm分ss秒') || '';
    console.log(_startDate,_newDate);
    startDate.value = _startDate;
    newDate.value = _newDate;
    console.log(newVal);
  });
  //保存数据
  function handleSave() {
    if (!isEdit.value) {
      ElMessage({
        type: 'warning',
        message: '抱歉，您没有权限编辑该模块数据'
      })
      return
    }

    formRef.value.validate(isValid => {
      if (isValid) {
        loading.value = true;
        let data = formRef.value.getData();
        data.row_id=activeRow_id.value
        editAllShuttle(data).then(res => {
          loading.value = false;
          if (res.errcode !== 0) return;
          readonly.value = true
          ElMessage({type: 'success',message: '修改成功'})
          emit('save')
        })
      }
    })
  }
  function handleSave2(obj) {
    formRef.value.validate(isValid => {
      if (isValid) {
        loading.value = true;
        let data = formRef.value.getData();
        data.row_id=activeRow_id.value
        editAllShuttle({...data, ...obj}).then(res => {
          loading.value = false;
          if (res.errcode !== 0) return;
          readonly.value = true
          // ElMessage({type: 'success',message: '修改成功'})
          emit('save')
          mData.value.shuttle_seat_id = obj.shuttle_seat_id
          mData.value.shuttle_seat_name = obj.shuttle_seat_name
        })
      }
    })
  }

  function togglePage(page) {
    activePage.value = page;
  }

  function getDetailData(shuttle_id) {
    getAllShuttle({shuttle_id}).then(res => {
      if (res.errcode !== 0)return;
      let data = res.row[0];
      let obj = {};
      activeRow_id.value = data.row_id
      fieldList.value.forEach(item =>{
        let val = data[item.show_field || item.field_id]
        val && (obj[item.field_id] = val)
      });
      mData.value = obj;
    })
  }

  function getRefPermission(){
    isSeeTicket.value = hasSeeAuthority('shuttlePackage')
    isSeeStop.value  = hasSeeAuthority('shuttleStop')
    isSeeSeat.value  = hasSeeAuthority('shuttleSeat')
    isSeeSchool.value  = hasSeeAuthority('shuttleSchool')
    isEdit.value = getAuthority('shuttle').is_edit;
  }

  provide('refresh', getDetailData)

</script>

<style scoped lang="less">
    @import '../../assets/css/pageDtl.less';
    .tips{
        height: 30px;
        display: flex;
        align-items: center;
        padding: 0 20px;
        /*justify-content: center;*/
    }
</style>
